# _*_ encoding:utf-8 _*_

from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.db.models import Q
from django.views.generic import View
# Create your views here.

from .models import UserProfile, EmailVarifyRecord
from .forms import UserLoginForm, RegisterForm, ForgetPwdForm, ModifyPwdForm
from .send_email import send_register_email


class CustomBackend(ModelBackend):
    def authenticate(self, request=None, username=None, password=None, **kargs):
        try:
            query = Q(username=username) | Q(email=username)
            user = UserProfile.objects.get(query)
            if user.check_password(password):
                return user
        except Exception:
            return None


class ActiveUserView(View):
    def get(self, request, active_code):
        form = self.get_validate_form(code=active_code)
        if isinstance(form, UserLoginForm):
            self.delete_code()
            return render(request, 'login.html', {'userlogin_form': form})
        elif isinstance(form, ModifyPwdForm):
            return render(request, 'password_reset.html', {'modify_pwd_form': form})
        else:
            return render(request, 'simple_msg.html', {'msg': u'验证链接失效.'})

    def get_validate_form(self, code):
        records = EmailVarifyRecord.objects.filter(code=code)
        for record in records:
            if record.send_type == 'forget':
                email = record.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
                userlogin_form = UserLoginForm({'username': user.username})
                return userlogin_form
            elif record.send_type == 'reset':
                email = record.email
                modify_pwd_form = ModifyPwdForm(
                    {'email': email, 'code': code})
                modify_pwd_form.errors.clear()
                return modify_pwd_form
        return None

    def delete_code(self, code):
        records = EmailVarifyRecord.objects.filter(code=code)
        records.delete()


class ModifyPwdView(View):
    def get(self, request):
        modify_pwd_form = ModifyPwdForm()
        modify_pwd_form.errors.clear()
        return render(request, 'password_reset.html', {'modify_pwd_form': modify_pwd_form})

    def post(self, request):
        modify_pwd_form = ModifyPwdForm(request.POST)
        if modify_pwd_form.is_valid():
            if modify_pwd_form['password1'].value() == modify_pwd_form['password2'].value():
                code = modify_pwd_form['code'].value()
                form = ActiveUserView().get_validate_form(code)
                if form is not None:
                    password = modify_pwd_form['password1'].value()
                    view_email = modify_pwd_form['email'].value()
                    if form['email'].value() == view_email:
                        users = UserProfile.objects.filter(email=view_email)
                        for user in users:
                            user.password = make_password(password)
                            user.save()
                            login_form = UserLoginForm(
                                {'username': view_email})
                            ActiveUserView().delete_code(code)
                            return render(request, 'login.html', {'userlogin_form': login_form})
                        modify_pwd_form.add_error('', '用户邮箱不存在.')
                    else:
                        modify_pwd_form.add_error('', '用户邮箱验证失效.')
                else:
                    modify_pwd_form.add_error('', '邮箱验码已经失效.')
            else:
                modify_pwd_form.add_error('', '两次输入的密码不一致.')
        return render(request, 'password_reset.html', {'modify_pwd_form': modify_pwd_form})


class ForgetPwdView(View):
    def get(self, request):
        forget_pwd_form = ForgetPwdForm()
        return render(request, 'forgetpwd.html', {'forget_pwd_form': forget_pwd_form})

    def post(self, request):
        forget_pwd_form = ForgetPwdForm(request.POST)
        if forget_pwd_form.is_valid():
            # email = request.POST.get('email')
            email = forget_pwd_form['email'].value()
            users = UserProfile.objects.filter(email=email)
            if len(users) == 0:
                forget_pwd_form.add_error('', u'邮箱未注册!')
            else:
                excute_msg = send_register_email(email, send_type='reset')
                if excute_msg == 'success':
                    return render(request, 'simple_msg.html', {'msg': u'密码重置链接已经发送到邮箱.'})
                else:
                    forget_pwd_form.add_error('', u'密码不正确!')
        return render(request, 'forgetpwd.html', {'forget_pwd_form': forget_pwd_form})


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        username = request.POST.get('email')
        email = request.POST.get('email')
        password = request.POST.get('password')
        if register_form.is_valid():
            users = UserProfile.objects.filter(
                Q(username=username) | Q(email=username))
            if len(users) == 0:
                msg = send_register_email(email, 'register')
                if msg == 'success':
                    register_form.success = True
                #     new_user = UserProfile()
                #     new_user.username = username
                #     new_user.email = email
                #     new_user.is_active = False
                #     new_user.password = make_password(password)
                #     new_user.save()
                #     userlogin_form = UserLoginForm(
                #         {'username': username, 'password': password})
                #     return render(request, 'login.html', {'userlogin_form': userlogin_form})
                else:
                    register_form.add_error('', u'验证码发送失败，请重试！\n' + msg)
            else:
                register_form.add_error('', '该邮箱已经注册！')
        return render(request, 'register.html', {'register_form': register_form})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        userlogin_form = UserLoginForm(request.POST)
        if userlogin_form.is_valid():
            user_name = request.POST.get('username')
            pass_word = request.POST.get('password')
            user = authenticate(
                request, username=user_name, password=pass_word)
            if user:
                if user.is_active:
                    login(request, user)
                    return render(request, 'index.html')
                else:
                    userlogin_form.add_error('', '用户邮箱未激活！')
                    return render(request, 'login.html', {'userlogin_form': userlogin_form})
            else:
                userlogin_form.add_error('', '用户名或密码错误！')
                return render(request, 'login.html', {'userlogin_form': userlogin_form})
        else:
            return render(request, 'login.html', {'userlogin_form': userlogin_form})


class LogoutView(View):
    def get(self, request):
        logout(request)
        return render(request, 'index.html', {})
